package domain.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.StringTokenizer;
import java.util.regex.Pattern;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import net.sf.jsr107cache.Cache;
import net.sf.jsr107cache.CacheException;
import net.sf.jsr107cache.CacheManager;

import domain.data.QnAPersistenceManager;
import domain.model.Domain;
import domain.model.InOutLink;
import domain.model.TrackIp;
import domain.model.Whois;
import domain.service.AgeDomain;
import domain.service.AlexaUpdate;
import domain.service.CheckDomain;
import domain.service.CheckRobotSitemap;
import domain.service.GooglePageRank;
import domain.service.Ip;
import domain.service.SelfSiteUpdate;
import domain.service.Utils;

@SuppressWarnings("serial")
public class SearchDomainServlet extends HttpServlet {
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		resp.setContentType("text/plain");
		resp.setCharacterEncoding("utf-8");
		PersistenceManager psm = QnAPersistenceManager.get().getPersistenceManager();
		String ip = req.getRemoteAddr();

        req.setAttribute("ip", ip);		
		String title_url = req.getParameter("name");
		title_url = title_url.toLowerCase().replaceAll("(http|https)+://(www.)*", "").replaceAll("^[\\w\\W]+[\\/]{2}", "").replaceAll("[\\/]+[\\w\\W]+$", "").replaceAll("www.", "");
		
		Query query = psm.newQuery(Domain.class);
		query.setFilter("name=='"+title_url+"'");
		@SuppressWarnings("unchecked")
		List<Domain> domains = (List<Domain>) query.execute();
		if(domains.size()>0)
		{
			Cache cache=null;

	        try {
	            cache = CacheManager.getInstance().getCacheFactory().createCache(Collections.emptyMap());
	        } catch (CacheException e) {
	           e.printStackTrace();
	           
	        }
	        if(cache.containsKey("lastPing"))
	        {
	        	@SuppressWarnings("unchecked")
				ArrayList<String> lastPing = (ArrayList<String>)cache.get("lastPing");
	        	if(lastPing.size()>19)
	        	{
	        		lastPing.remove(0);
	        		
	        		
	        	}
	        	if(!lastPing.contains(domains.get(0).getName()))
	        	lastPing.add(domains.get(0).getName());
	        	cache.put("lastPing", lastPing);
	        	
	        }
	        else
	        {
	        	
	        	ArrayList<String> lastPing = new ArrayList<String>();
	        	if(!lastPing.contains(domains.get(0).getName()))
	        	lastPing.add(domains.get(0).getName());
	        	cache.put("lastPing", lastPing);
	        }
			
	        if(domains.get(0).getGoogleAdsense()!=null&&domains.get(0).getGoogleAdsense().trim().length()>0)
	        {
	        	@SuppressWarnings("unchecked")
				List<Domain> sameAds=  (List<Domain>)psm.newQuery(Domain.class,"googleAdsense == '"+domains.get(0).getGoogleAdsense()+"'").execute();
	        	req.setAttribute("sameAds", domain.service.Utils.convert2DomainString( sameAds));
	        }
	        
	        if(domains.get(0).getGoogleAnalytic()!=null&&domains.get(0).getGoogleAnalytic().trim().length()>0)
	        {
	        	@SuppressWarnings("unchecked")
				List<Domain> sameAnalytic=  (List<Domain>)psm.newQuery(Domain.class,"googleAnalytic == '"+domains.get(0).getGoogleAnalytic()+"'").execute();
	        	req.setAttribute("sameAnalytic", domain.service.Utils.convert2DomainString( sameAnalytic));
	        }
			
	        if(domains.get(0).getIp()!=null&&domains.get(0).getIp().trim().length()>0)
	        {
	        	String[] listIp = domains.get(0).getIp().split("\n");
	        	String sameip = "";
	        	for(int i=0;i<listIp.length;i++)
				{
					PersistenceManager psms = QnAPersistenceManager.get().getPersistenceManager();
					@SuppressWarnings("unchecked")
					List<TrackIp> listDomain=  (List<TrackIp>)psms.newQuery(TrackIp.class,"ip == '"+listIp[i]+"'").execute();
					if(listDomain.size() > 0)
					{
						sameip += "<li><div class=\"left detail_left\">"+listIp[i]+"</div><div class=\"left detail_right\">"+listDomain.get(0).getDomainStrings().replaceAll("[ ]+[,]+[ ]+$","")+"</div></li>";
					}
				}
		        req.setAttribute("sameip",sameip);
	        }
	        
			Query query2 = psm.newQuery(InOutLink.class);
			query2.setFilter("inLink =='"+title_url+"'");
			query2.setRange(0,5);
			@SuppressWarnings("unchecked")
			List<InOutLink> outlink = (List<InOutLink>) query2.execute();
			req.setAttribute("outlink", outlink);
			
			Query query3 = psm.newQuery(InOutLink.class);
			query3.setFilter("outLink =='"+title_url+"'");
			query3.setRange(0,5);
			@SuppressWarnings("unchecked")
			List<InOutLink> inlink = (List<InOutLink>) query3.execute();
			req.setAttribute("inlink", inlink);
			
			req.setAttribute("domain", domains.get(0));
			
			Query query4 = psm.newQuery(Whois.class);
			query4.setFilter("name=='"+title_url+"'");
			@SuppressWarnings("unchecked")
			List<Whois> whois = (List<Whois>) query4.execute();
			req.setAttribute("whois", whois);
			
			Query query5 = psm.newQuery(Domain.class);
			query5.setFilter("domain=='"+Utils.returnDomain(title_url)+"' && name != '"+title_url+"'");
			@SuppressWarnings("unchecked")
			List<Domain> otherDomain = (List<Domain>) query5.execute();
			req.setAttribute("otherDomain", otherDomain);
			
			if(domains.get(0).getSex() == 1)
			{
				req.setAttribute("title", domains.get(0).getName());
				req.setAttribute("description", "Domain - View infomation site in domain , analysis, traffic details, rankings, contact email ,similar site, same owner site , same ip site, optimization and promotion reports.");
				req.setAttribute("keyword", "Domain name information,  Server information, Web site analysis, website traffic details, Website backlinks website IP, website ranking info");
			} else {
				req.setAttribute("title", Utils.returnDomain(title_url)+" "+domains.get(0).getName()+ " " +domains.get(0).getTitle());
				String des = (domains.get(0).getDescription()!=null)?domains.get(0).getDescription().getValue():""+"."+domains.get(0).getPopularKeywordToString()+"."+domains.get(0).getKeywordToString();
				if(des.length() > 250)
				{
					des = des.substring(0,250);
				}
				String key = domains.get(0).getName()+","+domains.get(0).getPopularKeywordToString()+"."+domains.get(0).getKeywordToString()+",Domain name information,  Server information, Web site analysis, website traffic details, Website backlinks website IP, website ranking info";
				if(key.length() > 250)
				{
					key = key.substring(0,250);
				}
				req.setAttribute("description", des);
				req.setAttribute("keyword", key);
			}
			
			try {
				req.getRequestDispatcher("/detail.jsp").forward(req, resp);
			} catch (ServletException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} else {
			if(CheckDomain.CheckDomain(title_url))
			{
				Domain domain = new Domain();
				domain.setName(title_url);
				psm.makePersistent(domain);
				
				new AgeDomain(title_url);
				new Ip(title_url);
				new GooglePageRank(title_url);
				new domain.service.Whois(title_url);
				new SelfSiteUpdate(title_url);
				new CheckRobotSitemap(title_url);
				
				@SuppressWarnings("unchecked")
				List<Domain> check =  (List<Domain>)psm.newQuery(Domain.class,"name == '"+title_url+"'").execute();
			    
			    if(check.get(0).getDescription()!= null && check.get(0).getDescription().equals("") || check.get(0).getDescription() ==  null)
			    {
			    	domain.setName("www."+domain.getName());
				    new SelfSiteUpdate(domain.getName());
			    }
				new AlexaUpdate(title_url);
				resp.sendRedirect("/domain/"+title_url);
			} else {
				resp.getWriter().println("Domain "+title_url+" does not exit");
			}
		}
	}
}
